
use std::env;
use sysinfo::{CpuRefreshKind, RefreshKind, System};
use tauri::Manager;
// use tauri_plugin_shell::process::Command;
// use tauri_plugin_shell::ShellExt;

// use sysinfo::{System, SystemExt, CpuExt};
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

// cpu总使用率
#[tauri::command]
fn global_cpu_use() -> f32 {
    let mut system = System::new_all(); // 初始化并收集所有信息
    system.refresh_cpu_all();
    let mut s =
        System::new_with_specifics(RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()));
    // Wait a bit because CPU usage is based on diff.
    std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
    // Refresh CPUs again to get actual value.
    s.refresh_cpu_usage();
    // 四舍五入到两位小数
    (s.global_cpu_usage() * 100.0).round() / 100.0
}

// cpu总使用率
#[tauri::command]
fn global_memory_use() -> f32 {
    let mut system = System::new_all(); // 初始化并收集所有信息
    system.refresh_memory();
    // 计算内存使用率
    let total_memory = system.total_memory();
    let used_memory = system.used_memory();
    let memory_usage = (used_memory as f32 / total_memory as f32) * 100.0;
    // 四舍五入到两位小数
    (memory_usage * 100.0).round() / 100.0
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_os::init())
        .plugin(tauri_plugin_shell::init())
        // 日志插件
        // .plugin(
        //     tauri_plugin_log::Builder::new()
        //         .targets([
        //             Target::new(TargetKind::Stdout),
        //             Target::new(TargetKind::LogDir { file_name: None }),
        //             Target::new(TargetKind::Webview),
        //         ])
        //         .build(),
        // )
        .plugin(tauri_plugin_pinia::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_sql::Builder::default().build())
        .plugin(tauri_plugin_opener::init())
        .setup(|app| {
            #[cfg(debug_assertions)] // 仅在调试构建时包含此代码
            {
                let window = app.get_webview_window("main").unwrap();
                window.open_devtools();
                window.close_devtools();
            }
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            greet,
            global_cpu_use,
            global_memory_use
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
